'use client';

import React, { useState } from 'react';
import { Layout } from '@/components/layout';
import { useApp } from '@/hooks';
import { ExportOptions, ExportFormat, ScheduleItem } from '@/types';
import Link from 'next/link';

const ExportPage: React.FC = () => {
  const { state } = useApp();
  const [exportOptions, setExportOptions] = useState<ExportOptions>({
    format: 'ics',
    includeDescription: true,
    includeLocation: true,
    includeSpeakers: true,
    timeZone: 'Asia/Shanghai'
  });

  const handleExport = () => {
    if (!state.userSchedule) return;

    const items = state.userSchedule.items;
    let content = '';

    switch (exportOptions.format) {
      case 'ics':
        content = generateICS(items);
        downloadFile(content, 'yunqi-schedule.ics', 'text/calendar');
        break;
      case 'json':
        content = JSON.stringify({
          schedule: state.userSchedule,
          exportedAt: new Date().toISOString(),
          options: exportOptions
        }, null, 2);
        downloadFile(content, 'yunqi-schedule.json', 'application/json');
        break;
      case 'csv':
        content = generateCSV(items);
        downloadFile(content, 'yunqi-schedule.csv', 'text/csv');
        break;
      default:
        alert('PDF导出功能即将推出');
    }
  };

  const generateICS = (items: ScheduleItem[]) => {
    const lines = [
      'BEGIN:VCALENDAR',
      'VERSION:2.0',
      'PRODID:-//云栖大会日程助手//CN',
      'CALSCALE:GREGORIAN',
      'METHOD:PUBLISH'
    ];

    items.forEach(item => {
      const startDate = formatICSDate(item.agendaItem.startTime);
      const endDate = formatICSDate(item.agendaItem.endTime);
      
      lines.push(
        'BEGIN:VEVENT',
        `UID:${item.agendaItem.id}@yunqi.com`,
        `DTSTART:${startDate}`,
        `DTEND:${endDate}`,
        `SUMMARY:${item.agendaItem.title}`,
        exportOptions.includeLocation ? `LOCATION:${item.agendaItem.location}` : '',
        exportOptions.includeDescription ? `DESCRIPTION:${item.agendaItem.description}` : '',
        'END:VEVENT'
      );
    });

    lines.push('END:VCALENDAR');
    return lines.filter(line => line).join('\r\n');
  };

  const generateCSV = (items: ScheduleItem[]) => {
    const headers = ['标题', '开始时间', '结束时间'];
    if (exportOptions.includeLocation) headers.push('地点');
    if (exportOptions.includeSpeakers) headers.push('演讲者');
    if (exportOptions.includeDescription) headers.push('描述');

    const rows = [headers.join(',')];

    items.forEach(item => {
      const row = [
        `"${item.agendaItem.title}"`,
        `"${item.agendaItem.startTime.toLocaleString('zh-CN')}"`,
        `"${item.agendaItem.endTime.toLocaleString('zh-CN')}"`
      ];
      
      if (exportOptions.includeLocation) {
        row.push(`"${item.agendaItem.location}"`);
      }
      if (exportOptions.includeSpeakers) {
        row.push(`"${item.agendaItem.speakers.map(s => s.name).join(', ')}"`);
      }
      if (exportOptions.includeDescription) {
        row.push(`"${item.agendaItem.description.replace(/"/g, '""')}"`);
      }
      
      rows.push(row.join(','));
    });

    return rows.join('\n');
  };

  const formatICSDate = (date: Date) => {
    return date.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
  };

  const downloadFile = (content: string, filename: string, mimeType: string) => {
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  if (!state.userSchedule || state.userSchedule.items.length === 0) {
    return (
      <Layout>
        <div className="container mx-auto px-4 py-20 text-center">
          <div className="text-6xl mb-4">📄</div>
          <h2 className="text-2xl font-bold text-foreground mb-4">没有可导出的日程</h2>
          <p className="text-muted mb-8">
            请先选择一些会议添加到您的日程中
          </p>
          <Link href="/recommendations" className="btn btn-primary px-8 py-3">
            去选择会议
          </Link>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto">
          <div className="text-center mb-8">
            <h1 className="text-3xl font-bold text-foreground mb-4">
              📄 导出我的日程
            </h1>
            <p className="text-lg text-muted">
              选择合适的格式导出您的云栖大会日程安排
            </p>
          </div>

          <div className="card mb-8 p-8">
            <h2 className="text-2xl font-bold text-foreground mb-8">导出设置</h2>
            
            {/* 导出格式 */}
            <div className="mb-8">
              <label className="block text-lg font-semibold text-foreground mb-4">
                导出格式
              </label>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {([
                  { value: 'ics', label: '日历文件 (.ics)', desc: '可导入到各种日历应用' },
                  { value: 'csv', label: 'Excel表格 (.csv)', desc: '可在电子表格中查看' },
                  { value: 'json', label: 'JSON数据 (.json)', desc: '结构化数据格式' },
                  { value: 'pdf', label: 'PDF文档 (.pdf)', desc: '打印友好格式（即将推出）' }
                ] as { value: ExportFormat; label: string; desc: string }[]).map(format => (
                  <label
                    key={format.value}
                    className={`
                      flex flex-col p-6 rounded-lg border-2 cursor-pointer transition-all duration-200 min-h-[100px] justify-center
                      ${exportOptions.format === format.value 
                        ? 'border-primary bg-primary/10 shadow-md' 
                        : 'border-border hover:border-primary/50 hover:shadow-sm'
                      }
                      ${format.value === 'pdf' ? 'opacity-50 cursor-not-allowed' : ''}
                    `}
                  >
                    <input
                      type="radio"
                      name="format"
                      value={format.value}
                      checked={exportOptions.format === format.value}
                      disabled={format.value === 'pdf'}
                      onChange={(e) => setExportOptions({
                        ...exportOptions,
                        format: e.target.value as ExportFormat
                      })}
                      className="sr-only"
                    />
                    <div className="font-semibold text-lg text-foreground">{format.label}</div>
                    <div className="text-sm text-muted mt-2 leading-relaxed">{format.desc}</div>
                  </label>
                ))}
              </div>
            </div>

            {/* 包含内容选项 */}
            <div className="mb-8">
              <label className="block text-lg font-semibold text-foreground mb-4">
                包含内容
              </label>
              <div className="space-y-4">
                {[
                  { key: 'includeDescription', label: '会议描述', desc: '详细的会议内容说明' },
                  { key: 'includeLocation', label: '会议地点', desc: '会议举办场所信息' },
                  { key: 'includeSpeakers', label: '演讲者信息', desc: '主讲人姓名和详情' }
                ].map(option => (
                  <label key={option.key} className="flex items-center space-x-4 cursor-pointer p-4 rounded-lg border border-border hover:bg-hover hover:border-primary/50 transition-all duration-200">
                    <input
                      type="checkbox"
                      checked={exportOptions[option.key as keyof ExportOptions] as boolean}
                      onChange={(e) => setExportOptions({
                        ...exportOptions,
                        [option.key]: e.target.checked
                      })}
                      className="w-5 h-5 text-primary border-border rounded focus:ring-primary"
                    />
                    <div className="flex-1">
                      <div className="font-semibold text-lg text-foreground">{option.label}</div>
                      <div className="text-sm text-muted mt-1 leading-relaxed">{option.desc}</div>
                    </div>
                  </label>
                ))}
              </div>
            </div>

            {/* 时区设置 */}
            <div className="mb-8">
              <label className="block text-lg font-semibold text-foreground mb-4">
                时区设置
              </label>
              <select
                value={exportOptions.timeZone}
                onChange={(e) => setExportOptions({
                  ...exportOptions,
                  timeZone: e.target.value
                })}
                className="w-full p-4 text-lg border-2 border-border rounded-lg bg-surface hover:border-primary/50 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all duration-200"
              >
                <option value="Asia/Shanghai">中国标准时间 (UTC+8)</option>
                <option value="UTC">协调世界时 (UTC)</option>
                <option value="America/New_York">美国东部时间</option>
                <option value="Europe/London">英国时间</option>
              </select>
            </div>

            {/* 导出按钮 */}
            <button
              onClick={handleExport}
              className="btn btn-primary w-full py-4 text-xl font-semibold"
            >
              📥 导出日程 ({state.userSchedule.items.length} 个会议)
            </button>
          </div>

          {/* 日程预览 */}
          <div className="card p-8">
            <h3 className="text-2xl font-bold text-foreground mb-6">
              日程预览 ({state.userSchedule.items.length} 个会议)
            </h3>
            <div className="space-y-4 max-h-80 overflow-y-auto">
              {state.userSchedule.items
                .sort((a, b) => a.agendaItem.startTime.getTime() - b.agendaItem.startTime.getTime())
                .map(item => (
                  <div key={item.id} className="flex items-center justify-between p-4 border-2 border-border rounded-lg hover:border-primary/30 hover:bg-hover transition-all duration-200">
                    <div className="flex-1 pr-4">
                      <div className="font-semibold text-lg text-foreground">{item.agendaItem.title}</div>
                      <div className="text-muted mt-2">
                        {item.agendaItem.startTime.toLocaleString('zh-CN')} - {item.agendaItem.endTime.toLocaleString('zh-CN')}
                      </div>
                    </div>
                    <div className="text-sm font-medium text-muted bg-border/50 px-3 py-1 rounded-full">
                      {item.agendaItem.location}
                    </div>
                  </div>
                ))}
            </div>
          </div>

          {/* 返回链接 */}
          <div className="text-center mt-12">
            <Link href="/schedule" className="btn btn-secondary px-8 py-3 text-lg">
              返回日程视图
            </Link>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default ExportPage;